<template>
  <section class="content">
    <div class="row">
      <div class="col-xs-12">
        <div class="box box-info">
          <div class="box-header" style="border-bottom: 1px solid rgb(226, 225, 225)">
            <h3 class="box-title">国收申报表头</h3>
          </div>
          <!-- /.box-header -->
          <div class="box-body">
            <div class="form-group">
              <div class="col-sm-12 p-r-0">
                <div class="row col-sm-3 flex">
                  <label for="" class="control-label min-width text-right"><sub class="text-red">*</sub>收款账号</label>
                  <div class="inline-block">
                    <input type="text" class="form-control" placeholder="请输入收款账号" v-model="payment">
                  </div>
                </div>
                <div class="row col-sm-3 flex">
                  <label for="" class="control-label min-width text-right"><sub class="text-red">*</sub>申报总额</label>
                  <div class="inline-block">
                    <div class="input-group">
                      <input type="text" class="form-control" placeholder="请输入申报总额" v-model="grossAmount">
                      <span class="input-group-addon">USD</span>
                    </div>
                  </div>
                </div>
                <div class="row col-sm-5 flex">
                  <label for="" class="control-label min-width text-right"><sub class="text-red">*</sub>日期范围</label>
                  <div class="inline-block">
                    <el-date-picker class="pull-left linehe" style="width: 46%;height: 36px;line-height: 34px"
                                    type="datetime" placeholder="开始时间" format="yyyy-MM-dd HH:mm:ss"
                                    value-format="yyyy-MM-dd HH:mm:ss" @change="getSTime" v-model="addForm.starTime">
                    </el-date-picker>
                    <span class="pull-left " style="line-height: 36px;padding: 0 1%">至</span>
                    <el-date-picker class="pull-left linehe" style="width: 46%" type="datetime" placeholder="结束时间"
                                    format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" v-model="addForm.endTime" @change="getETime">
                    </el-date-picker>
                  </div>
                </div>
                <div class="pull-right">
                  <button class="btn btn-success min-width" @click="getCustomsDeclara">筛选订单</button>
                </div>
              </div>
            </div>
          </div>
          <!-- /.box-body -->
        </div>
        <!-- /.box -->
      </div>
    </div>
    <div class="row form-group" v-if="">
      <div class="col-xs-12">
        <div class="box box-info">
          <div class="box-header" style="border-bottom: 1px solid rgb(226, 225, 225)">
            <h3 class="box-title">订单列表</h3>
            <button class="btn btn-primary min-width pull-right m-lr-10" v-if="$_has('sys:payment:export')" @click="u8OrderDownload">确认导出</button>
            <!--<button class="btn bg-green min-width pull-right">确认申报</button>-->
          </div>
          <!-- /.box-header -->
          <div class="box-body">
            <div class="row m-b-10">
              <div class="col-sm-12 flex">
                <label class="control-label min-width">订单编号</label>
                <div class="inline-block">
                  <input type="text" class="form-control pull-left" style="width: 350px" placeholder="请输入订单编号" v-model="orderNum">
                  <button class="btn btn-success pull-left m-lr-10" @click="searchOrderNum">查询</button>
                  <p class="pull-right control-label text-danger" v-if="customsDeclarationList.length != 0">
                    ${{totalPrice}}
                  </p>
                </div>
              </div>
            </div>
            <table class="table table-bordered table-responsive">
              <div class="overlay" v-if="show">
                <i class="fa fa-refresh fa-spin"></i>
              </div>
              <thead>
              <tr>
                <th>订单日期</th>
                <th>订单编号</th>
                <th>订单金额（USD）</th>
                <th>报关单号</th>
                <th>操作</th>
              </tr>
              </thead>
              <tbody>
              <tr v-if="customsDeclarationList.length == 0">
                <td colspan="6">
                  请筛选订单
                </td>
              </tr>
              <tr v-else v-for="(customsDeclarationListItem,index) in customsDeclarationList" :class="{'showActive':showActive}">
                <td >{{customsDeclarationListItem.orderCreated}}</td>
                <td>{{customsDeclarationListItem.orderId}}</td>
                <td class="text-right" style="padding-right: 20px;">${{customsDeclarationListItem.total}}</td>
                <td>{{customsDeclarationListItem.declareNo ? customsDeclarationListItem.declareNo : '-'}}</td>
                <td>
                  <a class="text-red" @click="deleteCustom(customsDeclarationListItem.orderId,customsDeclarationListItem.total)">删除</a>
                </td>
              </tr>
              </tbody>
            </table>
            <div class="clearfix"  v-if="customsDeclarationList.length != 0">
              <div class="pull-right">
                <pagination :total="pages.total" :current-page='pages.current'
                            :display="pages.display" @pagechange="pagechange"></pagination>
              </div>
            </div>
          </div>
          <!-- /.box-body -->
        </div>
        <!-- /.box -->
      </div>
    </div>
    <div class="modal fade" id="modal-default">
      <div class="modal-dialog maxwModal">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title">报关单模板下载</h4>
          </div>
          <div class="modal-body">
            <div class="box-body">
              <div class="minh">
                <div class="flex">
                  <label class="min-width control-label">模板下载：</label>
                  <div class="inline-block"><a href="">asdfa</a></div>
                </div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
          </div>
        </div>
        <!-- /.modal-content -->
      </div>
      <!-- /.modal-dialog -->
    </div>

    <transition name="fade">
      <div v-if="errorShow" class="gritter-notice-wrapper " :class="{'success-notice-wrapper':errorClass}">
        <div id="gritter-item-4" class="gritter-item-wrapper gritter-error" style="" role="alert">
          <div class="gritter-item"><a class="gritter-close" tabindex="1" @click="closeError"><i
            class="fa fa-close"></i></a>
            <div class="gritter-without-image"><span class="gritter-title">{{errorTitle}}</span>
              <p>{{errorMsg}}</p></div>
          </div>
        </div>
      </div>
    </transition>
  </section>
</template>

<script>
  import pagination from '@/components/common/pageComponent'
  import instance from '@/api/index.js'

  export default {
    name: "chargeDeclare",
    data() {
      return {
        show: false,//loading
        pages: {
          current: 1,//当前页
          display: 10,//每页显示多少条数据
          total: 0,//总条数
        },
        allList: [],
        customsDeclarationList: [],//获取报关单列表
        star: '',//开始日期
        end: '',//结束日期
        payment: '',//获取付款方式
        grossAmount:'',//总金额
        addForm:{},//开始日期结束日期
        errorShow: false,//错误显示
        errorMsg: '',//错误信息
        errorTitle: '',//错误提示标题
        errorClass: false,//错误样式
        listShow:false,//显示列表
        orderNum:'',//订单号查询
        customsDeclaraArr:[],//分页数组
        totalPrice:0,//总金额
        excelData:[],
        showActive:false,//查询第一条添加样式
        skipOrderIds:[],
      }
    },
    methods: {
      // 获取分页
      pagechange: function (currentPage) {
        this.pages.current = currentPage;
        if (this.orderNum && currentPage == 1) {
          this.showActive = true;
        }else {
          this.showActive = false;
        }
        this.customsDeclarationList = this.customsDeclaraArr.slice((currentPage - 1) * 10, currentPage * 10);
      },

      accAdd(arg1,arg2){
        var r1,r2,m;
        try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0};
        try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0};
        m=Math.pow(10,Math.max(r1,r2));
        //动态控制精度长度
        var n=(r1>=r2)?r1:r2;
        console.log("n: ", n); 
        return ((arg1*m+arg2*m)/m).toFixed(n);
      },

      getSTime:function(val){
        this.addForm.starTime = val;
      },
      getETime:function(val){
        this.addForm.endTime = val;
      },

      //获取国收申报列表
      getCustomsDeclara: function () {
        let vm = this;
        vm.skipOrderIds = [];
        if(!this.payment){
          // vm.errorClass = false;
          // vm.errorShow = true;
          // vm.errorTitle = "收款账号错误";
          // vm.errorMsg = "收款账号不能为空！";
          // vm.setTime();
          vm.$message.error('收款账号不能为空');
          return;
        }
        if(!this.grossAmount){
          // vm.errorClass = false;
          // vm.errorShow = true;
          // vm.errorTitle = "申请总额错误";
          // vm.errorMsg = "申请总额不能为空！";
          // vm.setTime();
          vm.$message.error('申请总额不能为空');
          return
        }
        if(this.addForm.starTime && this.addForm.endTime){
          var starTime = new Date(this.addForm.starTime.replace("-", "/").replace("-", "/"));
          var endTime = new Date(this.addForm.endTime.replace("-", "/").replace("-", "/"));
          if(starTime > endTime){
            // vm.errorClass = false;
            // vm.errorShow = true;
            // vm.errorTitle = "日期范围错误";
            // vm.errorMsg = "开始日期大于结束日期！";
            // vm.setTime();
            vm.$message.error('开始日期大于结束日期');
            return;
          }
        }else {
          // vm.errorClass = false;
          // vm.errorShow = true;
          // vm.errorTitle = "日期错误";
          // vm.errorMsg = "请选择日期！";
          // vm.setTime();
          vm.$message.error('请选择日期');
          return
        }


        // if(!this.payment || !this.grossAmount || !this.addForm.starTime || !this.addForm.endTime){}
        if(!this.grossAmount || !this.addForm.starTime || !this.addForm.endTime){
          // vm.errorClass = false;
          // vm.errorShow = true;
          // vm.errorTitle = "操作错误";
          // vm.errorMsg = "请输入相应内容！";
          // vm.setTime();
          vm.$message.error('请输入相应内容');
          return
        }else {
          instance({
            method: 'post',
            url: 'v1/order/orderDeclareRelation/getList',
            params: {
              account:vm.payment,
              total:vm.grossAmount,
              begin:vm.addForm.starTime,
              end:vm.addForm.endTime
            }
          }).then(function (data) {
            console.log(data)
            if(data.data.success){
              console.log(data)
              vm.skipOrderIds = [];
              vm.listShow = true;
              vm.customsDeclaraArr = data.data.data;
              if(vm.customsDeclaraArr.length != 0){
                vm.customsDeclarationList = vm.customsDeclaraArr.slice(0, 10);
              }
              vm.pages.total = vm.customsDeclaraArr.length;
              //计算总金额
              vm.computedPrice();
            }else {
                // vm.errorClass = false;
                // vm.errorShow = true;
                // vm.errorTitle = "操作错误";
                // vm.errorMsg = data.data.msg;
                // vm.setTime();
              vm.$message.error(data.data.msg);
            }
          })
        }
      },



      //计算总金额
      computedPrice:function(){
        this.totalPrice = 0;
        for (let k = 0; k < this.customsDeclaraArr.length; k++){
          this.totalPrice = this.accAdd(this.totalPrice, this.customsDeclaraArr[k].total);
        }
      },

      //导出到U8
      u8OrderDownload: function () {
        let vm = this;
        if (vm.customsDeclaraArr.length == 0){
          vm.$message.error('没有订单可导出！');
          return;
        }
        let param = {
          skipOrderIds:[],
        };
        param.begin = vm.addForm.starTime;
        param.end = vm.addForm.endTime;
        param.total = vm.grossAmount;
        param.account = vm.payment;
        param.skipOrderIds = vm.skipOrderIds;
        if(param.skipOrderIds.length == 0){
          param.skipOrderIds = [];
        }
        console.log(param);
        instance({
          method: 'post',
          url: '/v1/declare/export/payment?begin='+param.begin+'&end='+param.end+'&total='+param.total+'&account='+param.account+'&skipOrderIds='+param.skipOrderIds,
          // data:param,
          responseType: 'blob'
        }).then(function (data) {
          console.log(data)
          if (data.data.success) {
            vm.$alert('下载失败！', '提示', {
              confirmButtonText: '确定',
            });
          } else {
            vm.download(data);
          }
        });
      },
      // 下载文件
      download(data) {
        if (!data) {
          vm.$alert('下载失败！', '提示', {
            confirmButtonText: '确定',
          });
          return;
        }
        if(window.navigator.msSaveBlob){
          // for ie 10 and later
          try{
            let blob = new Blob([data.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
            window.navigator.msSaveBlob(blob, '国收申报.xlsx');
          }
          catch(e){
            console.log(e);
          }
        }else{
          let blob = new Blob([data.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
          let  url = URL.createObjectURL(blob);
          let link = document.createElement('a');
          link.style.display = 'none';
          link.href = url;
          link.setAttribute('download', '国收申报');
          document.body.appendChild(link);
          link.click();
          URL.revokeObjectURL(url);
        }
      },
      // //初始化页面基础数据

      //定时信息提示
      setTime: function () {
        let vm = this;
        setTimeout(function () {
          vm.errorShow = false;
        }, 2500)
      },

      //关闭信息提示
      closeError: function () {
        this.errorShow = false;
      },

      //搜索
      searchOrderNum:function(){
        let vm = this;
        if (vm.customsDeclaraArr.length == 0){
          vm.$message.error('没有订单可查询！')
        }

        if (this.orderNum) {
          this.showActive = true;
        }else {
          this.showActive = false;
        }
        for (let j = 0; j < vm.customsDeclaraArr.length; j++){
          if(vm.customsDeclaraArr[j].orderId == this.orderNum){
            let first = vm.customsDeclaraArr[0];
            vm.customsDeclaraArr[0] = vm.customsDeclaraArr[j];
            vm.customsDeclaraArr[j] = first;
          }
        }
        vm.customsDeclarationList = vm.customsDeclaraArr.slice(0, 10);
        console.log(vm.customsDeclaraArr)
      },

      accSubtr(arg1,arg2){
        var r1,r2,m,n;
        try{r1=arg1.toString().split(".")[1].length;}catch(e){r1=0;}
        try{r2=arg2.toString().split(".")[1].length;}catch(e){r2=0;}
        m=Math.pow(10,Math.max(r1,r2));
        //动态控制精度长度
        n=(r1>=r2)?r1:r2;
        return ((arg1*m-arg2*m)/m).toFixed(n);
      },

      //删除
      deleteCustom:function (_id,_total) {
        for (let l = 0; l < this.customsDeclaraArr.length; l++){
          if(this.customsDeclaraArr[l].orderId == _id){
            this.skipOrderIds.push(this.customsDeclaraArr[l].orderId);
            this.customsDeclaraArr.splice(l,1);
          }
        }
        this.showActive = false;
        this.totalPrice = this.accSubtr(this.totalPrice, _total);
        this.customsDeclarationList = this.customsDeclaraArr.slice((this.pages.current - 1) * 10, this.pages.current * 10);
        this.pages.total = this.customsDeclaraArr.length;
      },

      //添加样式
      chooseStatus: function (index) {
        this.activeIndex = index;
      },

      //测试
      // addList: function () {
      //   for (let i = 0; i < 20; i++) {
      //     let obj = {};
      //     obj.time = i + 1;
      //     this.allList.push(obj)
      //   }
      //   this.customsDeclarationList = this.allList.slice(0, 10);
      //   this.pages.total = this.allList;
      // },


    },
    created() {

      // this.addList();
    },
    watch:{
      grossAmount:function () {
        this.grossAmount = this.grossAmount.replace(/[^0-9\.]/g,'');
      }
    },
    components: {
      pagination
    }
  }
</script>

<style scoped>
  .linehe > input{
    line-height: 34px!important;
    height: 36px!important;
  }
  .el-input__inner{
    height: auto;
    line-height: normal;
  }
  .el-input__icon{
    line-height: 34px!important;
  }
</style>
